/**
 * Created with IntelliJ IDEA.
 * User: Joshua
 * Date: 8/15/12
 * Time: 5:59 PM
 * A javascript Controller for weapon functionality and operations.
 */

/*
* Functions to call on startup: this will include setting button even handlers
*/
$(document).ready(function(){
    //set the event handlers
    $('.refill').click(refill);
    $('.reload').click(reload);
    $('.fire').click(fire);
})

/////////////////////////////////////////////////////////////////////////////////
//event handler for refilling a clip
function refill(){
    //get the item to be refilled and the amount of available ammunition
    var clip = new Clip($(this).attr('data-clip'));
    var loose = parseInt($('#loose').text());

    var difference = clip.capacity - clip.quantity;
    if(difference > loose){ //the character doesn't have enough ammo to refill completely
        clip.quantity += loose;
        loose = 0;
    }else{
        clip.quantity = clip.capacity;
        loose -= difference;
    }

    //update the page
    clip.write();
    $('#loose').text(loose);
}

///////////////////////////////////////////////////////////////////////////////////////
//event handler for reloading with a clip
function reload(){
    var clip = new Clip($(this).attr('data-clip'));
    var loaded = new Clip('loaded');

    //swap the clips
    clip.write(loaded.id);
    loaded.write(clip.id);
}

////////////////////////////////////////////////////////////////////////////////////
//event handler for firing a weapon
function fire(){
    var clip = new Clip('loaded');

    if(clip.quantity > 0){
        clip.quantity--;
        clip.write();
    }
}

///////////////////////////////////////////////////////////////////////////////
//a constructor representing a clip object parsed from a clip string literal
function Clip(itemid){
    this.id = itemid;

    var fields = $('#'+itemid).text().split('/');
    this.quantity = parseInt(fields[0]);
    this.capacity = parseInt(fields[1]);
}

Clip.prototype = {
    write: function(id){
        var clipString = this.quantity +" / "+this.capacity;
        var location = id || this.id
        $('#'+location).text(clipString);

        //update the serial numbers
        $('#'+location).attr('data-serial', $('#'+this.id).attr('data-serial'));
    }

}